<template>
  <el-dialog class="public-dialog" :title="`${isEdit ? '修改' : '新增'}退换货`" width="1000" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <div>
      <!-- {{ props.id }}_ -->
      <FormTitle title="订单信息" />
      <div class="w-[300px]">
        <FormCombinedNorm v-model="noCombined" :options="orderNoOptions" :itemProps="{ onChange: handleChange, disabled: !!props.id }" :style="{ width: '400px' }">
          <template #default>
            <el-input v-model.trim="noCombined.value" @blur="handleBlur" clearable :disabled="!!props.id" placeholder="请输入" />
          </template>
        </FormCombinedNorm>
      </div>
      <!-- 订单信息 -->
      <div class="flex flex-wrap pt-[8px]">
        <Descriptions label-width="118px" v-for="item in orderInfo" :key="item.label" :label="item.label" :value="orderData?.[item.field] || '-'" />
      </div>
      <!-- 退款信息 -->
      <ReturnInfo ref="infoRef" class="mt-[8px]" :info="orderData" :disabled="disabled" @warehouse="handleWareHouse" />
      <!-- 仓库信息 -->
      <!-- <WareHouseInfo :data="warehouseInfo" class="mt-[8px]" /> -->
      <WareHouseInfo :data="orderData" class="mt-[8px]" />
      <!-- 退款产品 -->
      <ReturnProduct ref="productRef" class="mt-[8px]" :data="orderData?.items" :disabled="disabled" />
      <div class="mt-[16px]">
        <FormTitle title="备注信息" />
        <Editor :readOnly="disabled" v-model="remark" :min-height="100" />
      </div>
    </div>
    <template #footer>
      <el-button :disabled="loading" @click="handleClose(false)">
        {{ disabled ? "关闭" : "取消" }}
      </el-button>
      <el-button v-if="!disabled" type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus"
import FormCombinedNorm from "@/components/XForm/FormCombinedNorm.vue"

import FormTitle from "@/components/XForm/FormTitle.vue"
import Descriptions from "@/components/Descriptions/index.vue"
import Editor from "@/components/Editor/index.vue"
import ReturnInfo from "./ReturnInfo/index.vue"
import WareHouseInfo from "./WarehouseInfo/index.vue"
import ReturnProduct from "./ReturnProduct/index.vue"

// import orderApi from '@/views/user/list/add/api/index'
import orderApi from "@/views/user/list/add/api/index"
import { createExchange, exchangeDetail, updateExchange } from "../../api"

import { computed, nextTick } from "vue"

const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(["update:modelValue", "refresh", "close"])

const infoRef = ref()
const productRef = ref()
const noCombined = ref({ type: "order_sn" })
// const noCombined = ref({ type: 'order_sn', value: "1231215341885845" })
const loading = ref()
const orderData = ref()
const remark = ref("")
// const warehouseInfo = ref({})

const orderNoOptions = [
  { label: "系统订单号", value: "order_sn" },
  { label: "平台订单号", value: "platform_order_sn" },
]

const orderInfo = [
  { label: "平台/站点", field: "platformAll" },
  { label: "店铺", field: "shop" },
  { label: "下单时间", field: "order_time" },
  { label: "发货时间", field: "shipping_time" },
  { label: "收货国家", field: "country_name" },
  { label: "发货仓库", field: "ship_warehouse_name" },
  { label: "运输方式", field: "transport_name" },
]
watch(
  () => props.modelValue,
  (val) => {
    if (val && props.id) {
      nextTick(() => {
        getDetail(props.id)
      })
    }
  }
)
// watch(
//   () => props.id,
//   (val) => {
//     if (val) {
//       console.log(1111111)
//       nextTick(() => {
//         console.log(1223)
//         getDetail(val)
//       })
//     }
//   }
// )

const getDetail = async (id) => {
  try {
    const { data } = await exchangeDetail({ id })
    orderData.value = {
      ...data,
      items: data?.products?.map((n) => {
        return {
          ...n,
          quantity: n.shipmentsQuantity,
          count: n.quantity,
          id: n.order_item_id,
        }
      }),
      platformAll: `${data.platform}${data.site ? `/${data.site}` : ""}`,
      ship_warehouse_name: data.shipLogistics.ship_warehouse_name,
      transport_name: data.shipLogistics.transport_name,
    }
    remark.value = data.exchange_remark

    noCombined.value.value = data.order_sn
  } catch (e) {
    orderData.value = {}
    console.error(e)
  }
}

const handleChange = (e) => {
  const { value } = noCombined.value || {}
  nextTick(() => {
    if (value && value?.trim?.().length && e) {
      handleGetOrderInfo()
    }
  })
}

const handleWareHouse = (warehouseData) => {
  // const {
  //   id,
  //   warehouse_name,
  //   country,
  //   country_cn,
  //   zip_code,
  //   contacts,
  //   phone,
  //   address,
  // } = e || {}
  // warehouseInfo.value = {
  //   exchange_warehouse_id: id,
  //   exchange_warehouse_name: warehouse_name,
  //   warehouse_country_code: country,
  //   warehouse_country_name: country_cn,
  //   warehouse_post_code: zip_code,
  //   warehouse_contact_person: contacts,
  //   warehouse_contact_phone: phone,
  //   warehouse_address: address,
  // }
  orderData.value = {
    ...orderData.value,
    ...warehouseData,
  }
}

const handleBlur = () => {
  const _val = noCombined.value?.value
  if (_val && _val?.trim?.().length) {
    handleGetOrderInfo()
    return
  }
  orderData.value = {}
}

const handleGetOrderInfo = async () => {
  const _val = noCombined.value
  try {
    const { data } = await orderApi.orderDetail({ [_val?.type]: _val?.value })
    orderData.value = {
      ...data,
      platformAll: `${data.platform}${data.site ? `/${data.site}` : ""}/${data.shop}`,
      items: data?.items?.map((n) => ({ ...n, count: n.quantity > 0 ? 1 : 0, order_item_id: n.id })),
      ship_warehouse_name: data?.logistics?.ship_warehouse_name,
      // shipping_method_id: data?.logistics?.shipping_method_id,

      country_name: data?.recipient?.recipient_country,
      transport_name: data?.logistics?.transport_name,
    }
    if (orderData.value.order_status != 5) {
      ElMessage.warning("订单状态不为‘已发货’，不可申请退换货")
    }
  } catch (e) {
    orderData.value = {}
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const handleClose = (refresh) => {
  orderData.value = {}
  noCombined.value = { type: "order_sn" }
  remark.value = " "
  emit("update:modelValue", false)
  emit("close")
  if (refresh) emit("refresh")
}

const handleSave = async () => {
  console.warn(remark.value)

  try {
    if (!orderData.value?.order_sn) {
      ElMessage.warning("请先输入订单编号")
      return
    }
    loading.value = true
    await infoRef.value.form.submit()
    const productData = productRef.value.getTableData().tableData

    if (!productData?.length) {
      ElMessage.warning(`请先添加退货产品!`)
      return
    }
    const _emptyCount = productData.findIndex((n) => !n.count && +n.count < 1)
    if (_emptyCount > -1) {
      ElMessage.warning(`请补充第${_emptyCount + 1}个商品退货数量!`)
      return
    }

    console.warn(productData)
    const _emptyType = productData.findIndex((n) => !n.problem_type || (n.problem_type == 7 && !n.problem_description))
    if (_emptyType > -1) {
      ElMessage.warning(`请补充第${_emptyType + 1}个商品问题类型!`)
      return
    }
    const { id } = props
    const api = {
      edit: updateExchange,
      add: createExchange,
    }
    let baseInfoKey = [
      "customer_name",
      "customer_phone",
      "customer_email",
      "exchange_warehouse_id",
      "exchange_type",
      "exchange_tracking_number",
      "order_sn",
      "exchange_warehouse_id",
      "exchange_warehouse_name",
      "warehouse_country_code",
      "warehouse_country_name",
      "warehouse_post_code",
      "warehouse_contact_person",
      "warehouse_contact_phone",
      "warehouse_address",
    ]

    let baseInfo = {}
    baseInfoKey.forEach((key) => {
      baseInfo[key] = orderData.value[key]
    })

    let params = {
      // ...orderData
      id: id || undefined,
      // order_sn: orderData.value?.order_sn,
      ...baseInfo,
      // ...warehouseInfo.value,
      products: productData?.map((n) => ({
        ...n,
        quantity: n.count,
        item_id: n.id,
      })),
      exchange_remark: remark.value,
    }
    console.log(params)
    await api[isEdit.value ? "edit" : "add"](params)
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息")
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

defineExpose({
  noCombined,
  handleGetOrderInfo,
  handleChange,
})
</script>
<style lang="scss" scoped>
:deep(.form-title) {
  margin-bottom: 8px;
}
:deep(.descriptions) {
  margin-top: 0;
  margin-bottom: 16px;
}
</style>
